<template>
  <div>
    <div class="container">
      <el-input v-model="articleForm.articleTitle" placeholder="请输入文章标题" class="inline-input"></el-input>
       <el-button @click="handlePrview" type="primary" class="inline-button">预览文章</el-button>
       <el-button @click="handlerArticle" type="danger" class="inline-button">发布文章</el-button>
    </div>
    <el-row>
      <el-col :span="24" >
        <div>
          <v-md-editor
            v-model="articleForm.articleContent"
            :left-toolbar="left"
            :disabled-menus="[]"
            :include-level="[1, 2, 3, 4, 5]"
            :right-toolbar="right"
            :toolbar="toolbar"
            @upload-image="handleUploadImage"
            height="600px"
          ></v-md-editor></div
      ></el-col>
    </el-row>
    <div>
      <!-- 发布或修改对话框 -->
      <el-dialog title="发布文章" v-model="addOrUpdate" :visible.sync="dialogVisible" width="600px" top="0.5vh" append-to-body>
          <el-form ref="articleFormRef" label-width="80px" :model="articleForm" :rules="rules">
              <!-- 文章分类 -->
              <el-form-item label="文章分类" prop="categoryName">
                  <el-tag type="success" v-show="articleForm.categoryName" :disable-transitions="true" :closable="true"
                      @close="removeCategory">
                      {{ articleForm.categoryName }}
                  </el-tag>
                  <!-- 分类选项 -->
                  <el-popover v-if="!articleForm.categoryName" placement="bottom-start" width="460" trigger="click">
                  <el-button slot="reference" type="success" plain>添加分类</el-button>
                      <div class="popover-title">分类</div>
                      <!-- 搜索框 -->
                      <el-autocomplete style="width: 100%" v-model="categoryName" :fetch-suggestions="searchCategory"
                          placeholder="请输入分类名搜索,enter可添加自定义分类" :trigger-on-focus="false" @keyup.native.enter="saveCategory"
                          @select="handleSelectCategory">
                          <template #default="{ item }">
                              <div>{{ item.categoryName }}</div>
                          </template>
                      </el-autocomplete>
                      <!-- 分类 -->
                      <div class="popover-container">
                          <div v-for="item of categoryList" :key="item.id" class="category-item"
                              @click="addCategory(item.categoryName)">
                              {{ item.categoryName }}
                          </div>
                      </div>
                  </el-popover>
              </el-form-item>
              <!-- 文章标签 -->
              <el-form-item label="文章标签" prop="tagNameList">
                  <el-tag v-for="(item, index) of articleForm.tagNameList" :key="index" :disable-transitions="true"
                      :closable="true" @close="removeTag(item)" style="margin-right: 1rem;">
                      {{ item }}
                  </el-tag>
                  <!-- 标签选项 -->
                  <el-popover placement="bottom" width="460" trigger="click"
                      v-if="articleForm.tagNameList.length < 4">
                      <el-button slot="reference" type="primary" plain>添加标签</el-button>
                      <div class="popover-title">标签</div>
                      <!-- 搜索框 -->
                      <el-autocomplete style="width: 100%" v-model="tagName" :fetch-suggestions="searchTag"
                          placeholder="请输入标签名搜索,enter可添加自定义标签" :trigger-on-focus="false" @keyup.native.enter="saveTag"
                          @select="handleSelectTag">
                          <template #default="{ item }">
                              <div>{{ item.tagName }}</div>
                          </template>
                      </el-autocomplete>
                      <!-- 标签 -->
                      <div class="popover-container">
                          <div style="margin-bottom: 1rem">添加标签</div>
                          <el-tag v-for="(item, index) of tagList" :key="index" :class="tagClass(item.tagName)"
                              @click="addTag(item.tagName)" style="margin-right: 1rem;">
                              {{ item.tagName }}
                          </el-tag>
                      </div>
                  </el-popover>
              </el-form-item>
              <!-- 文章类型 -->
              <el-form-item label="文章类型" prop="articleType">
                  <el-select v-model="articleForm.articleType" placeholder="请选择类型">
                      <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
                      </el-option>
                  </el-select>
              </el-form-item>
              <!-- 缩略图 -->
              <el-form-item label="缩略图" prop="articleCover">
                  <el-upload drag :show-file-list="false" :headers="authorization" action="/api/admin/article/upload"
                    :on-progress="handleProgress"
                      accept="image/*" :before-upload="beforeUpload" :on-success="handleSuccess">
                      <i class="el-icon-upload" v-if="articleForm.articleCover === ''"></i>
                      <div class="el-upload__text" v-if="articleForm.articleCover === ''">
                          将文件拖到此处，或<em>点击上传</em>
                      </div>
                      <img v-else :src="articleForm.articleCover" width="360" />
                       <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过1MB</div>
                  </el-upload>
                   <el-progress v-if="progressFlag" :percentage="uploadPercentage"></el-progress>
              </el-form-item>
              <!-- 置顶 -->
              <el-form-item label="置顶" prop="isTop">
                  <el-switch v-model="articleForm.isTop" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <!-- 推荐 -->
              <el-form-item label="推荐" prop="isRecommend">
                  <el-switch v-model="articleForm.isRecommend" active-color="#13ce66" inactive-color="#ff4949"  :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <!-- 发布形式 -->
              <el-form-item label="发布形式" prop="status">
                  <el-radio-group v-model="articleForm.status">
                      <el-radio :label="1">公开</el-radio>
                      <el-radio :label="2">私密</el-radio>
                      <el-radio :label="3">草稿</el-radio>
                  </el-radio-group>
              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button v-if="articleForm.status != 3" type="primary" @click="submitForm">发布文章</el-button>
                  <el-button v-else type="danger" @click="submitForm">保存草稿</el-button>
                  <el-button @click="dialogVisible = false">取 消</el-button>
              </div>
          </template>
      </el-dialog>
      <!-- 查看文章对话框 -->
      <el-dialog :visible.sync="preview" title="预览文章">
        <v-md-editor  :value="articleForm.articleContent" mode="preview"></v-md-editor>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import { uploadImage, addArticle, getEditArticleInfo,updateArticle } from '@/api/article'
import {getTagList} from '@/api/tag'
import {getCategoryList} from '@/api/category'
import { get } from 'js-cookie';
import MarkdownIt from 'markdown-it'
import VueMarkdownEditor, { xss } from '@kangc/v-md-editor';
export default {
  data() {
    this.toolbar = {
      linecode: {
        title: "行内代码块",
        icon: "v-md-icon-line-code",
        action(editor) {
          editor.insert(function (selected) {
            const prefix = "`";
            const suffix = "`";
            const placeholder = "请输入代码";
            const content = selected || placeholder;
            return {
              text: `${prefix}${content}${suffix}`,
              selected: content,
            };
          });
        },
      },
      alignleft: {
        title: "左对齐",
        icon: "v-md-icon-align-left",
        action(editor) {
          editor.insert(function (selected) {
            const prefix = "::: align-left\n";
            const suffix = "\n:::";
            const placeholder = "左对齐文本";
            const content = selected || placeholder;
            return {
              text: `${prefix}${content}${suffix}`,
              selected: content,
            };
          });
        },
      },
      alignright: {
        title: "左对齐",
        icon: "v-md-icon-align-right",
        action(editor) {
          editor.insert(function (selected) {
            const prefix = "::: align-right\n";
            const suffix = "\n:::";
            const placeholder = "右对齐文本";
            const content = selected || placeholder;
            return {
              text: `${prefix}${content}${suffix}`,
              selected: content,
            };
          });
        },
      },
      aligncenter: {
        title: "居中对齐",
        icon: "v-md-icon-align-center",
        action(editor) {
          editor.insert(function (selected) {
            const prefix = "::: align-center\n";
            const suffix = "\n:::";
            const placeholder = "居中对齐文本";
            const content = selected || placeholder;
            return {
              text: `${prefix}${content}${suffix}`,
              selected: content,
            };
          });
        },
      },
      ctoc: {
        title: "生成锚点",
        icon: "v-md-icon-cmd",
        action(editor) {
          editor.insert(function (selected) {
            const content = selected || '';
            return {
              text: `[[toc]]`,
              selected: content,
            };
          });
        },
      },
    };
    return {
      uploadPercentage: 0, // 上传进度
      progressFlag:false,
      articleContent: "",
      left: "undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code linecode | alignleft alignright aligncenter | tip emoji save",
      right: "ctoc preview toc sync-scroll fullscreen",
      date:'2023-11-10',
      articleForm: {
        id: undefined,
        articleCover: "",
        articleTitle: '',
        articleContent: "",
        categoryName: "",
        tagNameList: [
       
        ],
        articleType: 1,
        isTop: 0,
        isRecommend: 0,
        status: 1,
    },
    typeList:[],
    tagList:[
    ],
    tagName:"",
    categoryName:'',
    categoryList:[
    ],
    addOrUpdate:false,
    typeList: [
    {
        value: 1,
        label: "原创",
    },
    {
        value: 2,
        label: "转载",
    },
    {
        value: 3,
        label: "翻译",
    },
    ],
    dialogVisible: false, // 添加此属性来控制弹出框的可见性
    preview:false,
    rules:{
    categoryName: [
      { required: true, message: '文章分类不能为空',   }
    ],
    tagNameList: [
      { required: true, message: '文章标签不能为空',   }
    ],
  },
    };
  },
  methods: {
    handleUploadImage() {},
    handlerArticle(){
        // 调用 validateForm 检查输入框和文章内容是否有效
      if (this.validateForm()) {
        //
        getTagList().then((data)=>{
          if(data.code == 200)
          {
            this.tagList = data.data;
          }
        }).catch((error)=>{
          console.log(error)
        })
        getCategoryList().then((data)=>{
          if(data.code == 200)
          {
            this.categoryList = data.data;
          }
        }).catch((error)=>{
          console.log(error)
        })
        // 如果有效，显示弹出框
        this.dialogVisible = true;
      } else {
        // 如果无效，显示错误消息或根据需要处理
        // 例如，您可以使用 Element UI 这样的 UI 库来显示消息
        this.$message({type:'error',message:'标题或内容不能为空'})
      }
    },
    beforeUpload(file){
   // 获取文件大小，单位为字节
      const fileSize = file.size;
      
      // 允许的文件类型数组
      const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg'];
      
      // 文件类型不在允许的类型列表中
      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只能上传jpg/png文件');
        return false; // 终止上传
      }
      let commonSize = 1024*1024;
      let roles = this.$store.state.user.roleList;
      if(roles != undefined && roles.length > 0)
      {
        if(roles.indexOf('1') != -1)
        {
          commonSize = 1024*1024*10;
        }
      }
      // 文件大小超过1MB
      if (fileSize > commonSize) {
        this.$message.error('文件大小不能超过1MB');
        return false; // 终止上传
      }
      
      return true; // 允许上传
    },
    //上传进度
     handleProgress(event, file, fileList) {
      this.progressFlag = true; // 显示进度条
      // 计算上传进度
      this.uploadPercentage = event.percent
      if(event.percent >= 99)
      {
        this.uploadPercentage = 99
      }
    },
    //上传成功
    handleSuccess(response, file){
      this.uploadPercentage = 100
      this.articleForm.articleCover = response.data
      this.$message({
        type: 'success',
        message: '上传成功!'
      })
    },
    handleSelectTag(item){
      this.addTag(item.tagName);
    },
    searchTag(searchString ,cb){
      var tagList = this.tagList;
      var results = searchString ? tagList.filter(this.createFilter(searchString)) : tagList;
      cb(results);
    },
    createFilter(searchString){
      return (tag) => {
        return (tag.tagName.toLowerCase().indexOf(searchString.toLowerCase()) === 0);
      };
    },
    handleSelectCategory(item){
      this.addCategory(item.categoryName);
    },
    searchCategory(searchString,cb){
      var categoryList = this.categoryList;
      var results = searchString ? categoryList.filter(this.createCategoryFilter(searchString)) : categoryList;
      cb(results);
    },
    createCategoryFilter(searchString){
      return (category) => {
        return (category.categoryName.toLowerCase().indexOf(searchString.toLowerCase()) === 0);
      };
    },
    removeCategory(){
      this.articleForm.categoryName = "";
    },
    //提交表单
    submitForm(){
      this.$refs.articleFormRef.validate((valid) => {
        if (valid) {
          if(this.articleForm.id == undefined)
          {
            addArticle(this.articleForm).then((data)=>{
              if(data.code == 200)
              {
                this.$message({type:'success',message:'发布成功！'})
                this.articleForm = {
                          id: undefined,
                          articleCover: "",
                          articleTitle: '',
                          articleContent: "",
                          categoryName: "",
                          tagNameList: [],
                          articleType: 1,
                          isTop: 0,
                          isRecommend: 0,
                          status: 1,
                };
                this.dialogVisible = false;
              }
            }).catch((error)=>{
              console.log(error)
            })
          }
          else
          {
            updateArticle(this.articleForm).then((data)=>{
              if(data.code == 200)
              {
                this.$message({type:'success',message:'修改成功！'})
                this.articleForm = {
                          id: undefined,
                          articleCover: "",
                          articleTitle: '',
                          articleContent: "",
                          categoryName: "",
                          tagNameList: [],
                          articleType: 1,
                          isTop: 0,
                          isRecommend: 0,
                          status: 1,
                };
                this.dialogVisible = false;
                this.$router.push({path:'/article/list'})
              }
            }).catch((error)=>{
              console.log(error)
            })
          }
     
        } else {
          this.$message.error('表单验证失败');
        }
      });
    },
    // 添加一个验证表单的方法
    validateForm() {
      // 检查标题和内容是否不为空
      if (this.articleForm.articleTitle.trim() === '' || this.articleForm.articleContent.trim() === '') {
        return false; // 标题或内容为空，返回 false
      }
      return true; // 标题和内容都不为空，返回 true
    },
    //选择标签
    addTag(item){
      if(this.articleForm.tagNameList.indexOf(item) == -1)
      {
        this.articleForm.tagNameList.push(item);
      }
    },
    //移出标签
    removeTag(item){
      const index = this.articleForm.tagNameList.indexOf(item);
      if (index !== -1) {
        this.articleForm.tagNameList.splice(index, 1);
      }
    },
    saveTag(){
      if(this.tagName.trim() != ''){
        this.addTag(this.tagName)
        this.tagName = "";
      }
    },
    saveCategory(){
      if(this.categoryName.trim() != ''){
        this.addCategory(this.categoryName)
        this.categoryName = "";
      }
    },
    addCategory(item){
      this.articleForm.categoryName = item;
    },
    handleUploadImage(event, insertImage, files) {
      uploadImage(files).then((data)=>{
        if(data.code == 200){  
        this.$message({type:'success',message:'上传成功！'})
        insertImage({
          url: data.data,
        });
        }
      }).catch((error)=>{
        console.log(error)
      })
    },
    handlePrview(){
      this.preview = true      
    }
  },
  computed: {
    //获取文章内容
    authorization() {
      const token = getToken()
      return {token}
    },
    tagClass(item){
        return function (item) {
        const index = this.articleForm.tagNameList.indexOf(item);
        return index !== -1 ? "tag-item-select" : "tag-item";
    };
    }
  },
  mounted(){
     const articleId = this.$route.params.articleId;
     if(articleId)
     {
      getEditArticleInfo(articleId).then((data)=>{
        if(data.code == 200)
        {
          this.articleForm = data.data;
          this.transMarkDown();
        }
      }).catch((error)=>{
        console.log(error)
      })
     }
  }
};
</script>

<style>
.v-md-icon-line-code::before {
  content: "{\\}";
  font-weight: bold; /* 将图标加粗 */
}

/* 文本靠左对齐的图标 */
.v-md-icon-align-left::before {
  content: "\2190"; /* 使用Unicode字符表示一个左箭头 */
  margin-right: 5px; /* 可选的右侧间距 */
}

/* 文本靠右对齐的图标 */
.v-md-icon-align-right::before {
  content: "\2192"; /* 使用Unicode字符表示一个右箭头 */
  margin-left: 5px; /* 可选的左侧间距 */
}

/* 文本居中对齐的图标 */
.v-md-icon-align-center::before {
  content: "\2194"; /* 使用Unicode字符表示一个双向箭头 */
  font-weight: bold; /* 添加加粗样式 */
}

.v-md-icon-cmd::before {
  content: "生成锚点";
}

.container {
  display: flex; /* 使用 Flex 布局 */
  align-items: center; /* 垂直居中对齐 */
  padding-left: 11px;
  padding-right: 13px;
  padding-top: 15px;
}

.inline-input {
  /* 可选样式，控制输入框的外观 */
  padding: 5px;
}

.inline-button {
  /* 可选样式，控制按钮的外观 */
  margin-left: 10px; /* 可选的按钮与输入框之间的间距 */
}

.operation-container {
    display: flex;
    align-items: center;
    margin-bottom: 1.25rem;
}

.md-container {
    min-height: 300px;
    height: calc(100vh - 200px);
}


.popover-title {
    margin-bottom: 1rem;
    text-align: center;
}

.popover-container {
    margin-top: 1rem;
    height: 260px;
    overflow-y: auto;
}

.category-item {
    cursor: pointer;
    padding: 0.6rem 0.5rem;
}

.category-item:hover {
    background-color: #f0f9eb;
    color: #67c23a;
}

.tag-item {
    margin-right: 1rem;
    margin-bottom: 1rem;
    cursor: pointer;
}

.tag-item-select {
    margin-right: 1rem;
    margin-bottom: 1rem;
    cursor: not-allowed;
    color: #ccccd8 !important;
}
</style>